<template>
  <div v-loading="loading" class="app-container details salesOrder-details">
    <el-row :gutter="20">
      <!--产品分类-->
      <el-col :span="5" class="details-left box-card">
        <el-card>
          <!-- 系统介绍 -->
          <div class="details-left-top details-left-box">
            <!-- 项目才显示图标 -->
            <!-- <i class="el-icon-s-tools"></i> -->
            <div class="top">
              <svg-icon
                :icon-class="'svg_salesorder'"
                class="block w-80px h-80px m-auto mb-15px"
              />
              <label>{{ formData.title }}</label>
              <p>{{ formData.number }}</p>
              <!-- <p>{{ formData.contractOrderNumber }}</p> -->
            </div>
            <!-- <el-row :gutter="24" class="mt-10px">
                          <el-col
                            :span="12"
                            class="border-r-2 border-fuchsia-600 border-gray-100 border-r-solid"
                          >
                            <p class="text-gray-700 font-bold text-base">1/10</p>
                            <p class="text-sm mt-10px">工单</p>
                          </el-col>
                          <el-col :span="12">
                            <p class="text-gray-700 font-bold text-base">1/10</p>
                            <p class="text-sm mt-10px">任务</p>
                          </el-col>
                        </el-row> -->
          </div>
          <div class="details-left-box">
            <!-- <div class="title">项目资产概况</div> -->
            <div class="cnt">
              <el-row :gutter="24" class="btn-box">
                <el-col :span="12">
                  <el-button
                    class="w-full"
                    type="primary"
                    @click="handleFollowUp"
                    >写新跟进</el-button
                  >
                </el-col>
                <el-col :span="12">
                  <el-button
                    class="w-full"
                    plain
                    type="primary"
                    @click="handleCollaborate"
                    >添加协作</el-button
                  >
                </el-col>
                <el-col :span="12">
                  <el-button
                    class="w-full"
                    plain
                    type="primary"
                    @click="handleUpload"
                    >添加附件</el-button
                  >
                </el-col>
                <el-col :span="12">
                  <el-button
                    class="w-full"
                    plain
                    type="primary"
                    @click="addTask"
                    >添加任务</el-button
                  >
                </el-col>
                <el-col :span="12">
                  <el-button
                    :disabled="
                      formData.oppositeId !== null ||
                      formData.property == '1' ||
                      formData.synchronousStatus !== '2'
                    "
                    class="w-full"
                    plain
                    type="primary"
                    @click="reversalOrder"
                    >冲红</el-button
                  >
                </el-col>
                <el-col :span="12">
                  <el-button
                    class="w-full"
                    plain
                    type="primary"
                    @click="copySalesOrderCopy"
                    >再来一单</el-button
                  >
                </el-col>
                <el-col :span="12">
                  <el-dropdown class="w-full">
                    <el-button class="w-full" plain type="primary">
                      合同
                      <el-icon class="el-icon--right"><CaretBottom /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="addLocationContract"
                          >本地合同</el-dropdown-item
                        >
                        <el-dropdown-item
                          :disabled="
                            formData.contractStatus == '1' ||
                            formData.contractStatus == '2' ||
                            formData.contractStatus == '3' ||
                            formData.contractStatus == '5'
                          "
                          @click="clickNuonuo()"
                          >诺诺合同</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-col>
                <el-col :span="12">
                  <el-button
                    :disabled="formData.status !== '5'"
                    class="w-full"
                    plain
                    type="primary"
                    @click="handleSalesSlip"
                    >签购单</el-button
                  >
                </el-col>
                <el-col :span="12">
                  <el-button
                    :disabled="
                      !(
                        formData.synchronousStatus == '2' &&
                        formData.warehouseStatus != '2'
                      )
                    "
                    class="w-full"
                    plain
                    type="primary"
                    @click="handleA8Outbound"
                    >同步A8出库</el-button
                  >
                </el-col>
                <el-col :span="12">
                  <el-button
                    class="w-full"
                    plain
                    type="primary"
                    @click="selectPro"
                    >关联项目</el-button
                  >
                </el-col>
                <el-col v-if="formData.source == 2" :span="12">
                  <el-button
                    class="w-full"
                    plain
                    type="primary"
                    @click="selectQRcode"
                    >推送至小程序</el-button
                  >
                </el-col>
              </el-row>
            </div>
          </div>
          <div class="details-left-box">
            <el-descriptions
              :column="1"
              :size="'small'"
              border
              title="订单信息"
            >
              <template #title>
                <div class="text-5">订单信息</div>
              </template>
              <el-descriptions-item label="客户名称" label-class-name="w-3/6">{{
                formData.customerName
              }}</el-descriptions-item>
              <el-descriptions-item label="订单金额(元)">{{
                formData.price
              }}</el-descriptions-item>
              <el-descriptions-item label="已回款金额(元)">{{
                formData.repaymentPrice
              }}</el-descriptions-item>
              <el-descriptions-item label="业务板块">
                <dict-drop
                  :options="order_business_type"
                  :value="formData.businessType"
                ></dict-drop>
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <div class="details-left-box">
            <div class="title">所属信息</div>
            <ul class="cnt status-box">
              <li>
                <el-icon><Notebook /></el-icon>
                <label>所属公司</label>
                <p>{{ formData.deptName }}</p>
              </li>
              <li>
                <el-icon><Notebook /></el-icon>
                <label>业务部门</label>
                <p>{{ formData.transactionDeptName }}</p>
              </li>
              <li>
                <el-icon><Notebook /></el-icon>
                <label>业务员</label>
                <p>{{ formData.transactionName }}</p>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
      <el-col :span="19" class="box-card" style="min-height: 800px">
        <el-card class="details-right" style="min-height: 100%">
          <el-tabs v-model="activeName" class="details-right-tabs">
            <template v-for="(item, index) in tabsList" :key="index">
              <el-tab-pane
                v-if="item.show"
                :label="item.label"
                :name="item.name"
              >
              </el-tab-pane>
            </template>
            <div>
              <component
                :is="components[activeName]"
                ref="tabName"
                v-bind="componentData"
                @parentFu="
                  () => {
                    getFormData(formData.id)
                  }
                "
              />
              <!--
                              :orderData="formData"
                              :orderId="formData.id" -->
            </div>
          </el-tabs>
        </el-card>
      </el-col></el-row
    >

    <!-- 状态更新对话框 -->
    <el-dialog
      v-model="statusBox.open"
      :title="statusBox.title"
      :width="statusBox.width"
      append-to-body
      @close="cancel"
    >
      <el-form
        ref="statusRef"
        :model="statusForm"
        :rules="statusRules"
        label-width="140px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品名称" prop="name">
              <el-input
                v-model="statusForm.name"
                disabled
                placeholder="请输入产品名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="产品状态" prop="label">
              <el-select
                v-model="statusForm.status"
                class="w-full"
                placeholder="请选择产品状态"
              >
                <el-option
                  v-for="item in enable_status"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="更新说明" prop="description">
              <el-input
                v-model="statusForm.description"
                maxlength="100"
                placeholder="请输入更新说明"
                rows="4"
                show-word-limit
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 跟进弹窗 -->
    <FollowUp
      :dialogParam="followUpParam"
      @close="
        () => {
          followUpParam.isVisible = false
          closeUp()
        }
      "
    ></FollowUp>

    <!-- 添加附件弹窗 -->
    <Appendix
      v-model="appendixParam.isVisible"
      :dialogParam="appendixParam"
      @close="
        () => {
          appendixParam.isVisible = false
          closeUp()
        }
      "
    ></Appendix>

    <!-- 新建任务 -->
    <TaskFrom :dialogParam="taskParam" @closeDialog="closeTask"></TaskFrom>

    <!-- 诺诺合同选择 -->
    <NuonuoContract
      v-if="nuonuoParam.visible"
      :relatedParams="nuonuoParam"
      @clickOK="() => getFormData(formData.id)"
      @closeDialog="
        () => {
          nuonuoParam.visible = false
        }
      "
    />

    <!-- 冲红弹窗 -->
    <InvoiceDialog
      v-model="redInvoiceParam.open"
      :dialogData="redInvoiceParam"
    />

    <!-- 签购单 -->
    <SalesSlip v-if="salesSlipDia.open" :dialogParam="salesSlipDia" />

    <!-- 关联合同 -->
    <SelectContract
      :dialogParam="diaParam"
      @close="diaParam.open = false"
      @ok="saveFn"
    />

    <!-- 选择合同 -->
    <!-- <RelatedContract
          :relatedParams="params"
          @closeDialog="closeDialog"
          @relatedOver="relatedOver"
          @editContract="editContract"
          ref="relatedContract"
        >
          <template #bottomBtn>
            <el-input
              v-show="showInput"
              placeholder="请输入合同备注"
              v-model="formData.contractRemark"
              class="mr-10px"
              style="width: 300px"
            />
            <el-button @click="showInput = !showInput" type="primary"
              >合同备注</el-button
            >
            <el-button @click="uploadConstarct" type="primary">上传合同</el-button>
          </template>
        </RelatedContract> -->

    <!-- 上传合同 -->
    <!-- <el-dialog title="上传合同" v-model="showUpload">
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="handleFileChange"
            accept=".rar, .zip, .doc, .docx, .pdf ,.jpg ,.png"
            :show-file-list="false"
            :multiple="true"
          >
            <el-button type="primary" style="font-size: 14px"
              ><el-icon> <UploadFilled /> </el-icon>上传合同</el-button
            >
            <template #tip>
              <span class="el-upload__tip ml-5px">
                支持格式：.rar .zip .doc .docx .pdf .jpg .png ，单个文件不能超过20MB
              </span>
            </template>
          </el-upload>
          <div class="text-14px mt-10px" style="width: 100%">
            <div v-for="(item, index) in fileList" :key="item.fileId">
              <span style="color: #409eff" :href="item.url">{{
                item.origFileName
              }}</span>
              <el-button text plain @click="delFileName(index)">删除</el-button>
            </div>
          </div>
          <template #footer>
            <div>
              <slot name="bottomBtn"></slot>
              <el-button @click="cancelUpload">取消</el-button>
              <el-button type="primary" @click="finishedUpload">确定</el-button>
            </div>
          </template>
        </el-dialog> -->

    <!-- 选择项目 -->
    <RelatedProject
      :relatedParams="proParams"
      @closeDialog="closePro"
      @relatedOver="relatedPro"
    />
  </div>
</template>
<script name="SalesOrderDetails" setup>
import { reactive, toRefs, ref, createApp, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  getSalesOrderDetail,
  orderUploadContract,
  salesOrderCopy,
  handleOutbound,
  relatedProject
} from '@/api/indentManage/indent'
import { supervisionContract } from '@/api/supervision/contract'
import {
  order_business_type //订单业务板块
} from '@/hooks/dict/order'
import useTagsViewStore from '@/store/modules/tagsView'
import ApprovalRecord from './approvalRecord'
import Overview from './overview'
import OrderProduct from './orderProduct'
import OrderOutbound from './orderOutbound'
import RepaymentInfo from './repaymentInfo'
import DetailsVIP from './detailsVIP'
import SalesSlip from './salesSlip'
import InvoiceRecord from '@/businessComponents/InvoiceRecord'
import FollowUpList from '@/businessComponents/FollowUpList'
import FollowUp from '@/businessComponents/FollowUp'
import AppendixList from '@/businessComponents/AppendixList'
import Appendix from '@/businessComponents/Appendix'
import OperationLog from '@/businessComponents/OperationLog'
import TaskFrom from '@/views/rsgl/taskManage/modules/add.vue' /* 添加任务弹窗 */
import taskDetailsForm from '@/views/salesManage/businessManage/businessDetails/modules/taskDetails.vue'
import RelatedContract from '@/components/RelatedContract/index.vue' /* 任务列表 */
import {
  uploadFile,
  delFile,
  contractInfoSave,
  contractInfoUpdate,
  contractDetails
} from '@/api/salesManage/contractManage'
import { checkAppletQrCode } from '@/api/otherBusinesses'
import { ElMessageBox } from 'element-plus'
import qrcode from 'qrcode'
const router = useRouter()
const route = useRoute()
const { proxy, type } = getCurrentInstance()
const activeName = ref('Overview')
const formData = ref({})
const components = shallowRef({
  ApprovalRecord,
  Overview,
  OrderProduct,
  OrderOutbound,
  RepaymentInfo,
  InvoiceRecord,
  FollowUpList,
  AppendixList,
  taskDetailsForm,
  DetailsVIP,
  SalesSlip,
  OperationLog
})
const data = reactive({
  loading: false,
  tabsList: [
    {
      label: '审批记录',
      name: 'ApprovalRecord',
      show: true,
      data: {
        baseDetail: computed(() => {
          return { titleName: '订单审批', ...formData.value }
        })
      }
    },
    {
      label: '概况信息',
      name: 'Overview',
      show: true,
      data: {
        orderData: computed(() => {
          return formData.value
        })
      }
    },
    {
      label: '产品记录',
      name: 'OrderProduct',
      show: true,
      data: {
        orderId: computed(() => {
          return formData.value.id
        }),
        tableParam: computed(() => {
          return formData.value
        })
      }
    },
    {
      label: '出库记录',
      name: 'OrderOutbound',
      show: true,
      data: {
        orderId: computed(() => {
          return formData.value.id
        }),
        tableParam: computed(() => {
          return formData.value
        })
      }
    },
    {
      label: '回款情况',
      name: 'RepaymentInfo',
      show: true,
      data: {
        orderId: computed(() => {
          return formData.value.id
        })
      }
    },
    {
      label: '发票记录',
      name: 'InvoiceRecord',
      show: true,
      data: {
        tableParam: computed(() => {
          return {
            id: formData.value.id,
            type: 'order',
            orderType: formData.value.orderType
          }
        })
      }
    },
    {
      label: '跟进记录',
      name: 'FollowUpList',
      show: true,
      data: {
        tableParam: computed(() => {
          return {
            businessId: formData.value.id, //业务id
            busineName: formData.value.title, //业务名称
            tableName: 'ord_order' //业务类型  biz_customer  客户页面  ord_project  项目  ord_order订单
          }
        })
      }
    },
    {
      label: '相关附件',
      name: 'AppendixList',
      show: true,
      data: {
        tableParam: computed(() => {
          return {
            businessId: formData.value.id, //业务id
            busineName: formData.value.title, //业务名称
            tableName: 'ord_order' //业务类型  biz_customer  客户页面  ord_project  项目  ord_order订单
          }
        })
      }
    },
    {
      label: '任务详情',
      name: 'taskDetailsForm',
      show: true,
      data: {
        taskParam: computed(() => {
          return {
            businessType: '2',
            businessId: formData.value.id, //业务id
            businessName: formData.value.title //标题
          }
        })
      }
    },
    {
      label: '会员权益',
      name: 'DetailsVIP',
      show: false,
      data: {
        param: computed(() => {
          return {}
        })
      }
    },
    {
      label: '操作日志',
      name: 'OperationLog',
      show: true,
      data: {
        tableParam: computed(() => {
          return {
            businessId: formData.value.id, //业务id
            busineName: formData.value.title, //业务名称
            tableName: 'ord_order' //业务类型  biz_customer  客户页面  ord_project  项目  ord_order订单
          }
        })
      }
    }
  ],
  componentData: [],

  statusBox: {
    title: '状态更新',
    open: false,
    width: '800px'
  },

  statusForm: {},
  statusRules: {},
  followUpParam: {}, // 跟进弹窗配置
  appendixParam: {}, // 附件弹窗配置
  nuonuoParam: {
    visible: false
  } // 诺诺合同弹窗配置
})
let {
  loading,
  tabsList,
  componentData,
  statusBox,
  statusForm,
  statusRules,
  followUpParam,
  appendixParam,
  nuonuoParam
} = toRefs(data)

watch(
  [() => route.query.salesOrderId, () => route.query.tabPane],
  async () => {
    if (route.query.salesOrderId) {
      console.log('这是详情！')
      await getFormData(route.query.salesOrderId)
      // statusForm.value.name = formData.value.name
    }
    if (route.query.tabPane) {
      activeName.value = route.query.tabPane
      // statusForm.value.name = formData.value.name
    }
  },
  {
    immediate: true
  }
)
// watch(
//   () => [formData], //[passData.data, data.crudData],
//   (newVal, oldValue) => {
//     statusForm.value.name = formData.value.name
//   },
//   { deep: true }
// )
onMounted(() => {
  componentData.value = computed(() => {
    let val = tabsList.value.filter(e => {
      return e.name == activeName.value
    })
    // console.log('val[0].data==>', val[0].data)
    return val[0].data
  })
})

const taskParam = ref({})

// 新建任务
const addTask = () => {
  //   taskParam.value.isVisible = true
  //   taskParam.value.businessType = '2'
  //   taskParam.value.businessId = formData.value.id
  //   taskParam.value.businessName = formData.value.title
  let object = {
    businessType: '2',
    businessId: formData.value.id,
    businessName: formData.value.title
  }
  router.push({
    path: '/rsgl/other/addTasking',
    query: { taskParam: JSON.stringify(object) }
  })
}

// 任务关闭
const closeTask = () => {
  taskParam.value.isVisible = false
  closeUp()
}

/** 获取产品详情
 * @param {number}  id 表单id
 */
async function getFormData(id) {
  loading.value = true
  let res = await getSalesOrderDetail(id)
  loading.value = false
  if (res.code !== 200) return
  formData.value = res.data
  console.log('formData.value', formData.value)
}

const redInvoiceParam = ref({
  open: false
})
// 点击冲红
async function reversalOrder() {
  //订单红字
  redInvoiceParam.value.open = true
  redInvoiceParam.value.isSelection = false
  redInvoiceParam.value.dialogType = '冲红'
  redInvoiceParam.value.query = {
    orderId: formData.value.id,
    openStatus: '1'
  }
  // let res = await reversalSalesOrder(formData.value.id)
  // if (res.code !== 200) return
  // getFormData(formData.value.id)
  // console.log('res==>', res)
  // goTo('/sales/indent/editSalesOrder', { salesOrderId: res.data.id })
}
//===================二维码生成 推送至小程序  gao 2024/5/10 =========//
let qrCodeData = ref('') //二维码信息
const selectQRcode = async () => {
  console.log(formData.value.source, 'source')
  let res = await checkAppletQrCode({ orderId: formData.value.id })
  if (res.code !== 200) {
    return false
  }
  const qrCodeDatas =
    import.meta.env.VITE_GZH_URL +
    '/pdfHtml/protocolPreview?orderNo=' +
    formData.value.contractOrderNumber
  qrcode.toDataURL(qrCodeDatas, (err, url) => {
    if (err) {
      console.error(err, '222222')
    } else {
      qrCodeData.value = url
      console.log(qrCodeDatas, '-成功二维码--')
    }
  })
  const html =
    '<div style=""><img src="' +
    qrCodeData.value +
    '" alt="QR Code"  style=" margin: auto;display: block;"/><div><p>注意:</p><p>1、请将二维码发送给客户，由客户进行扫码</p><p>2、成功扫码，订单信息将传到该客户账户下</p><p>3、该码仅由一位客户进行扫码</p></div></div>'
  ElMessageBox.alert(html, '推送至小程序', {
    dangerouslyUseHTMLString: true
  })
}
//===================二维码生成  gao 2024/5/10  end=========//
function goTo(url, data) {
  router.push({ path: url, query: data })
}
// 初始化
function init() {
  //   getFormData(route.query.productId)
  //   statusForm.value.name = formData.value.name
}
function cancel() {
  statusBox.value.open = false
  reset()
}
function submitForm() {
  console.log('statusForm.value', statusForm.value)
  // changeProductStatus(statusForm.value).then(res => {
  //   statusBox.value.open = false
  //   proxy.$modal.msgSuccess('修改成功')
  //   reset()
  // })
}

/** 表单重置 */
function reset() {
  statusForm.value = {}
  proxy.resetForm('statusRef')
}

// 跟进附件弹出关闭刷新列表
function closeUp() {
  let id = formData.value.id
  formData.value.id = ''
  formData.value.id = id
  // console.log('toRaw-tabsList==>', toRaw(tabsList.value))
  // console.log('tabsList==>', tabsList.value)
}

// 跟进
function handleFollowUp() {
  /***订单模块 */
  console.log('row==>', formData)
  followUpParam.value.isVisible = true
  followUpParam.value.tableName = 'ord_order'
  followUpParam.value.businessId = formData.value.id
  followUpParam.value.customer = formData.value.customerName
  followUpParam.value.orderName = formData.value.title
}
// 协作
function handleCollaborate() {}
// 附件
function handleUpload() {
  console.log('appendixParam==>', appendixParam)
  appendixParam.value.isVisible = true
  appendixParam.value.tableName = 'ord_order'
  appendixParam.value.businessId = formData.value.id
}

/* 添加本地合同  开始 */
const diaParam = ref({})
//打开上传合同弹窗
function addLocationContract() {
  /***订单模块 */
  diaParam.value.open = true
  diaParam.value.multiple = true // 是否多选
  diaParam.value.title = formData.value.customerName //名称 -- 显示dialog title
  diaParam.value.queryParams = {
    partya: formData.value.customerId, // 根据客户id查询合同列表
    uploadType: '1'
  }
  diaParam.value.initData = {
    customerName: formData.value.customerName, //甲方签约人
    customerId: formData.value.customerId, //合同甲方
    deptName: formData.value.deptName, //乙方签约人
    deptId: formData.value.deptId, //合同乙方
    title: formData.value.title, //props.dialogParam.initData.title, //合同名称
    receiptsDate: formData.value.receiptsDate, //签订时间

    contractList:
      formData.value.contractIds && formData.value.contractIds.length > 0
        ? formData.value.contractIds.map((e, i) => {
            return {
              rcId: e,
              contractName: formData.value.contractNames[i]
            }
          })
        : []
  }
}

// 确认关联合同
function saveFn(data) {
  console.log('data=>', data)
  let param = {
    contractList: data.selectData.filter(e => e.rcId),
    contractRemark: data.formData.contractRemark,
    orderId: formData.value.id
  }
  supervisionContract(param).then(res => {
    getFormData(formData.value.id)
  })
}
/* 添加本地合同  结束 */

const params = ref({})
const showInput = ref(false)
// 选中本地合同
// function addLocationContract() {
//   params.value = {
//     visible: true, // 显示dialog
//     businessId: formData.value.customerId, // 根据id查询合同列表
//     businessName: formData.value.customerName, // 名称 -- 显示dialog title
//     multiple: true, // 是否多选
//     defaultSelect: formData.value.contractIds ? formData.value.contractIds : [], // 默认选择数据
//     uploadType: '1'
//   }
//   // goTo('/sales/indent/editSalesOrder', {
//   //   salesOrderId: formData.value.id,
//   //   openDialog: 'contract'
//   // })
// }

// 关闭弹窗
function closeDialog() {
  params.value.visible = false
}

// 弹窗确认完成回调
function relatedOver(val) {
  const ids = val.map(v => v.rcId) || []
  formData.value.contractIds = ids
  formData.value.contractNames = val.map(v => v.contractName)
  orderUploadContract({
    id: formData.value.id,
    contractIds: ids,
    contractNames: formData.value.contractNames,
    contractRemark: formData.value.contractRemark
  }).then(res => {
    closeDialog()
  })
}

const selected = ref()
const constractParams = ref({})
// 更新合同方法
function editContract(val) {
  if (val.uploadType) {
    selected.value = val
    proxy.$modal
      .confirm('当前操作将前往更新合同的附件信息，是否继续操作')
      .then(() => {
        // 调用详情接口获取附件信息
        contractDetails(val.rcId)
          .then(res => {
            console.log(res)
            if (res.data) {
              fileList.value = res.data.sysAttachFiles || []
            }
          })
          .finally(() => {
            // 更新合同参数
            isUpdateConstract.value = true
            showUpload.value = true
          })
      })
  } else {
    selected.value = null
  }
}

// 上传合同
const showUpload = ref(false)
const isUpdateConstract = ref(false) // 是否更新合同信息
function uploadConstarct() {
  showUpload.value = true
  isUpdateConstract.value = false
}

// 删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    console.log(error)
  }
}

// 取消上传
function cancelUpload() {
  showUpload.value = false
}
const fileList = ref([]) // 文件列表
// 上传前检查文件类型大小
function beforeUpload(rawFile) {
  const type = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType =
    ['.rar', '.zip', '.doc', '.docx', '.pdf', '.jpg', '.png'].indexOf(type) < 0
  if (allowType) {
    proxy.$message.error(
      '上传文件只能是rar、zip、doc、docx、pdf、jpg、png格式!'
    )
    return false
  }
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
  return true
}

// 上传方法
async function handleFileChange(params) {
  const result = beforeUpload(params.file)
  if (!result) return
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    } else {
      console.log(res.msg)
    }
  } catch (error) {
    console.error(error)
  }
}
// 确认上传
const relatedContract = ref()
function finishedUpload() {
  if (fileList.value.length <= 0) {
    cancelUpload()
    return
  }
  constractParams.value.partyaSig = formData.value.customerName //customerOption.value['customerId'][0].label // 签约人甲方
  constractParams.value.partya = formData.value.customerId
  constractParams.value.partyaName = constractParams.value.partyaSig
  constractParams.value.partybSig = formData.value.deptName
  // companyOption.value[0].children.find(
  //   v => v.id === formData.value.deptId
  // ).label // 签约人乙方
  constractParams.value.partyb = formData.value.deptId
  constractParams.value.partybName = constractParams.value.partybSig
  constractParams.value.contractName = formData.value.title //合同名称
  constractParams.value.contractAttribute = '1' // 合同类别
  constractParams.value.uploadType = 1 // 订单添加合同标志位
  // constractParams.value.contractNum = '0000' // 合同编号
  // constractParams.value.contractSum = formData.value.price //合同金额
  constractParams.value.businessType = '0' // 合同类别
  constractParams.value.sinTime = formData.value.receiptsDate // 合同签约时间
  // constractParams.value.businessCategorize = formData.value.businessType //  所属业务分类
  constractParams.value.pbAlonePay = '2'
  constractParams.value.sysAttachFiles = fileList.value
  constractParams.value.fileNames = fileList.value.map(v => v.fileName)
  if (isUpdateConstract.value) {
    constractParams.value.rcId = '' //selected.value.rcId
    contractInfoUpdate(constractParams.value).then(res => {
      proxy.$refs.relatedContract.getList()
      fileList.value = []
      cancelUpload()
    })
  } else {
    contractInfoSave(constractParams.value).then(res => {
      if (res.data && Array.isArray(formData.value.contractIds)) {
        formData.value.contractIds.push(res.data)
      }
      proxy.$refs.relatedContract.getList()
      fileList.value = []
      cancelUpload()
    })
  }
}
// 选择诺诺合同
function clickNuonuo() {
  nuonuoParam.value.id = formData.value.id
  nuonuoParam.value.visible = true
  nuonuoParam.value.params = { ...formData.value }
}

// 签购单
const salesSlipDia = ref({
  open: false,
  queryParam: {}
})
const handleSalesSlip = () => {
  salesSlipDia.value = {
    open: true,
    title: '签购单',
    queryParam: {
      orderId: formData.value.id
    }
  }
}

// 再来一单
async function copySalesOrderCopy() {
  let res = await salesOrderCopy(formData.value.id)
  if (res.code !== 200) return
  getFormData(formData.value.id)
  console.log('res==>', res)
  goTo('/sales/indent/editSalesOrder', { salesOrderId: res.data.id })
}
// 同步A8出库
const handleA8Outbound = () => {
  handleOutbound(formData.value.id).then(res => {
    proxy.$modal.msgSuccess('同步成功')
    getFormData(formData.value.id)
  })
}

/****    关联项目  开始  ***/
const proParams = ref({
  visible: false,
  businessId: '',
  businessName: '客户名称'
})
// 打开弹窗
function selectPro() {
  const id = formData.value.customerId
  if (!id) {
    proxy.$modal.msgError('请先选择客户名称')
    return false
  }
  const ids = formData.value.projectId
  proParams.value = {
    visible: true, // 显示dialog
    businessId: id, //客户id
    businessName: formData.value.customerName, //客户名称
    multiple: false, // 是否多选
    defaultSelect: ids ? ids : [] // 默认选择数据
  }
  // 注意： 如果不需要选客户名称的话，这个businessId，businessName 可以不传
}

// 弹窗确认完成回调
async function relatedPro(val) {
  if (val) {
    const name = proParams.value.multiple
      ? val.map(v => v.proName).toString() || ''
      : val.proName

    const ids = proParams.value.multiple
      ? val.map(v => v.projectId) || []
      : val.projectId

    // formData.value.projectId = ids
    // formData.value.projectName = proParams.value.multiple
    //   ? val.map(v => v.proName)
    //   : name
    let data = {
      id: formData.value.id,
      projectId: ids
    }
    let res = await relatedProject(data)
    if (res.code != 200) return
    getFormData(formData.value.id)
  }
  closePro()
}

// 关闭弹窗
function closePro() {
  proParams.value.visible = false
}

/****    关联项目  end   ***/

init()
</script>
<style lang="scss" scoped>
@import '@/assets/styles/detailsStyle.scss';
</style>
